package com.fkdx.webman.controller;

import com.fkdx.common.enums.sys.GroupException;
import com.fkdx.common.token.TokenDomain;
import com.fkdx.common.utils.VerifyCodeUtils;
import com.fkdx.service.UserService;
import com.fkdx.service.dto.UserLoginReq;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
@Api(tags = "LoginController", value = "/login", description = "用户登录相关接口")
public class LoginController {

  private final Cache<String, Integer> cacheCodeName = CacheBuilder.newBuilder().
    expireAfterWrite(5, TimeUnit.MINUTES)
    .build(new CacheLoader<String, Integer>() {
      @Override
      public Integer load(String key) {
        return null;
      }
    });
  @Resource
  private UserService userService;

  @PostMapping(value = "/web/employee")
  @ApiOperation(value = "web员工登录", response = TokenDomain.class, httpMethod = "POST")
  public TokenDomain login(@RequestBody @Valid UserLoginReq req) {
    if(StringUtils.isEmpty(req.getCode())) {
      throw new GroupException("请输入验证码");
    }
    Integer num = cacheCodeName.getIfPresent(req.getCode());
    if (num == null || num == 0) {
      throw new GroupException("验证码错误");
    }
    cacheCodeName.invalidate(req.getCode());
    return userService.login(req);
  }

  /**
   * 生成验证码
   */
  @GetMapping("/web/getImage")
  public void getImage(HttpServletResponse response) throws IOException {
    //生成验证码
    String securityCode = VerifyCodeUtils.getSecurityCode();
    //将验证码放入session
    cacheCodeName.put(securityCode.toLowerCase(), 1);
    //生成图片
    BufferedImage image = VerifyCodeUtils.createImage(securityCode);
    //输出图片
    ServletOutputStream outputStream = response.getOutputStream();
    //调用工具类
    ImageIO.write(image,"png",outputStream);
  }

}
